#! encoding: utf-8
import requests
import time
from PIL import Image
import tempfile
import os
from concurrent.futures import ThreadPoolExecutor


try:
    from urllib.parse import urlencode
except:
    from urllib import urlencode

    
def log(*arg,**args):
    print(*arg,**args)
    
    
class CFG(object):
    def __init__(self,url, loginName, password):
        self.baseUrl = url
        self.loginName = loginName
        self.password = password
        self.path = '/Login.jsp'
        self.params = {}
        self.headers = {
            "Accept-Language":
            "zh-CN",
            "User-Agent":
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
            "Content-Type":
            "application/x-www-form-urlencoded",
            "Accept-Encoding":
            "gzip, deflate",
            "Content-Length":
            "81",
            "DNT":
            "1",
            "Connection":
            "Keep-Alive",
            "Cache-Control":
            "no-cache",
        }
        self.encode = 'utf-8'
        self.cookies = {}
        self.session = requests.session()

    def _set_cookie(self, cookie):
        self.cookies = cookie
        log('set cookie: {}'.format(self.cookies))

    def _get(self, url, params=None):
        log('-get- -url-:{} \t '.format(url))
        log('-get- -params-:{} \t '.format(params))
        r = self.session.get(
            url, params=params, headers=self.headers, )
        r.encoding = self.encode
        log('-get- -full url-',r.url)
        # self._set_cookie(r.cookies)
        # log('-get- -response-',r.text)
        return r

    def _post(self, url, body):
        log('-post- -url-:{} \t '.format(url))
        log('-post- -body-:{} \t '.format(body))
        r = self.session.post(
            url, data=body, headers=self.headers)
        r.encoding = self.encode
        log('-post- -full url-',r.url)
        # self._set_cookie(r.cookies)
        # log('-post- -response-',r.text)
        return r

    def _get_verifCode(self):
        params = {
            'ACT': 'verifCode',
            'timestamp': int(time.time() * 100),
        }
        url = self.baseUrl + '/loginAction.do'
        r = self._get(url, params)
        return r.content

    def _get_verifCodetext(self):
        imgb = self._get_verifCode()

        output_filename = os.path.join(tempfile.gettempdir(),'verifycode')
  
        output_filename = 'verifycode.jpg'
        with open(output_filename, 'wb') as wf:
            wf.write(imgb)

        img = Image.open(output_filename)
        img.show()
        
        text = input('enter the verif code: ')
        return text

    def login(self):
        url = self.baseUrl + '/Login.jsp'
        self._get(url, )
        url = self.baseUrl + '/loginAction.do'

        verifCode = self._get_verifCodetext()
        url += ';jsessionid='
        url += self.session.cookies.get('jsessionid') or ''
        body = dict(
            areacode='CD',
            loginname=self.loginName,
            userpassword=self.password,
            verifCodeIn=verifCode,
            B_SUBMIT='Login',
        )
        body = urlencode(body)

        r = self._post(url, body=body)
        return r

    def query_all_device_base(self,base_dev_info):

        base_body = '''oltDeviceId=&oltPortId=&loginuser=&busi_type=&bindNum=&B_LFIBER=%3CIMG+border%3D0+src%3D%22Images%2Fpreview.gif%22+align%3DabsMiddle%3EQuery&B_LFIBER=%3CIMG+border%3D0+src%3D%22Images%2Fclose.gif%22+align%3DabsMiddle%3ERelease&bindstatus=&dev_id=&anid=&lcode=&lanname=&lan_id=&oltDevName=&oltDevId=&memo=Bas&basportName=&basport=&portcode=&portLcode=&loid=&custname=&cust_id=&oltPort=&tmpSourcefile1=&ROWID_Grid1=&ID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&ROWID_Grid1=&SEL_PAGE='''
        b_p = dict(
            pmbName='',
            pmbId='',
            basDevName='',
            basDevId='',
        )
        b_p.update(base_dev_info)
        other_body = urlencode(b_p)
        # body = base_body + other_body
        
        all_devices = []
        for pageindex in range(1,501):
            path = '/dataCircuitAction.do?ACT=FTTHQUERY&OP=REMOVE&needMutiSelectDevice=0&PAGEINDEX=' 
            url = self.baseUrl + path + str(pageindex)
            body = base_body + str(pageindex) + '&' + other_body
            log('--query all device ---body--- {}'.format(body))
            r = self._post(url,body=body)
            devices = self.paser_device(r.text)
            if len(devices) < 1:
                break
            all_devices.extend(devices)
            
        return all_devices

    def paser_device(self, data):
        devices = []
        for line in data.split('\n'):
            line = line.strip()
            
            if line.startswith('Grid1.addData'):
                # log('--paser_device-- --line before--',line)
                line = line.replace('Grid1.addData','')
                line = line.replace(';','')
                # log('--paser_device-- --line after--',line)
                devices.append(eval(line))
        return devices

    def release_device(self, base_dev_info, device_customer_name=None):
        path = '/dataCircuitAction.do?ACT=RELEASEFTTH&OP=REMOVE&RELEASEID='
        
        base_body ="""oltDeviceId=&oltPortId=&loginuser=&busi_type=&bindNum=&B_LFIBER=%3CIMG+border%3D0+src%3D%22Images%2Fpreview.gif%22+align%3DabsMiddle%3EQuery&B_LFIBER=%3CIMG+border%3D0+src%3D%22Images%2Fclose.gif%22+align%3DabsMiddle%3ERelease&dev_id=&anid=&lcode=&lanname=&lan_id=&oltDevName=&oltDevId=&memo=Bas&basportName=&basport=&portcode=&portLcode=&loid=&custname=&cust_id=&oltPort=&tmpSourcefile1=&"""
        base_params = dict(
            pmbName='',
            pmbId='',
            basDevName='',
            basDevId='',
        )

        device_p = dict(
            ROWID_Grid1='',
            ID_Grid1='',
            )
        base_params.update(base_dev_info)
        base_params.update(device_p)
        devices = self.query_all_device_base(base_dev_info)
        # log('---devices---',devices)
        log('---devices--- --len---',len(devices))
        if  device_customer_name:
            temp_l = filter(lambda x: x[6] == device_customer_name, devices)
            devices = temp_l
        log('---start release port---')
        # for device in devices:
        #     base_params['ID_Grid1']= device[0]
        #     other_body = urlencode(base_params)
        #     body = base_body + other_body
        #     url = self.baseUrl + path + device[0]
        #     r = self._post(url,body=body)
        #     log('release port: ',device[0])
        #     # log(r.text)
            
        pool = ThreadPoolExecutor(10)
        for device in devices:
            base_params['ID_Grid1']= device[0]
            other_body = urlencode(base_params)
            body = base_body + other_body
            url = self.baseUrl + path + device[0]
            pool.submit(self._post, url, body)
            # r = self._post(url,body=body)
            log('release port: ',device[0])

        return
            
            
        pass

if __name__ == '__main__':
    config =dict(
        url='http://192.168.240.13:8001',
        loginName='test',
        password='Huawei@123',
    )
    base_dev_info = dict(
        pmbName='VTE_HOME_01',
        pmbId='204A63A0627211E896FAD7D67F000001',
        basDevName='VTE_HOME_01-Access_Equipment_Room01/FVTE_HW_ME60_BRAS01',
        basDevId='B30EAF80649C11E8AAF2E0AB7F000001',
    )
    c = CFG(**config)
    r = c.login()
    c.release_device(base_dev_info,)

